/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.planx.xmlstore.routing;

import tokyocabinet.HDB;

/**
 *
 * @author shiva
 */
public class StoreUtil {
    HDB map;

    public StoreUtil(HDB map){
        this.map = map;
    }

    public TimestampedValue get(String key){
        try{
            byte[] value = map.get(key.getBytes());
            if(value!=null){
                TimestampedValue object = (TimestampedValue)Kademlia.toObject(value);
                return object;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public TimestampedValue get(Identifier key){
        try{
            byte[] value = map.get(key.toByteArray());
            if(value!=null){
                TimestampedValue object = (TimestampedValue)Kademlia.toObject(value);
                return object;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public boolean put(String key, TimestampedValue value){
        try{
            byte[] data = Kademlia.getBytes(value);
            if(data == null){
                Throwable t = new Throwable();
                t.printStackTrace();
                System.exit(-1);
            }
            map.put(key.getBytes(),data);
             
            return true;
        }catch(Exception e){
            
        }
        return false;
    }

    public boolean put(Identifier key, TimestampedValue value){
        try{
            byte[] data = Kademlia.getBytes(value);
            if(data == null){
                Throwable t = new Throwable();
                t.printStackTrace();
                System.exit(-1);
            }
            map.put(key.toByteArray(),data);
            return true;
        }catch(Exception e){

        }
        return false;
    }

    public boolean remove(String key){
        try{
            map.out(key.getBytes());
            return true;
        }catch(Exception e){

        }
        return false;

    }


   public boolean remove(Identifier key){
        try{
            map.out(key.toByteArray());
            return true;
        }catch(Exception e){

        }
        return false;

    }

    public boolean containsKey(String key){
       try{
            byte[] value = map.get(key.getBytes());
            if(value!=null){
                return true;
            }
        }catch(Exception e){

        }
        return false;
    }

    public boolean containsKey(Identifier key){
       try{
            byte[] value = map.get(key.toByteArray());
            if(value!=null){
                return true;
            }
        }catch(Exception e){

        }
        return false;
    }

}
